package com.bubblegumproject.ogo.component;

import com.bubblegumproject.ogo.OgoException;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Utility class describing a 'setter' method that takes a single parameter and initializes some property on the
 * component class.
 *
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class Setter {

    private Method method;

    private Class argumentType;

    public Setter(Method method) {
        assert(method != null);
        if (!Modifier.isPublic(method.getModifiers()))
            throw new IllegalArgumentException(method + " is not a valid setter: it's not public");

        if (method.getParameterTypes().length != 1)
            throw new IllegalArgumentException(method + " is not a valid setter: it must take a single argument");

        this.method = method;
        this.argumentType = method.getParameterTypes()[0];
    }

    public Class getArgumentType() {
        return argumentType;
    }

    public void set(Object obj, Object value) {
        try {
            method.invoke(obj, value);
        } catch (Exception e) {
            throw new OgoException("failed to set value=" + value + " to method=" + method +
                    " on component=" + obj, e);
        }
    }

    public String toString() {
        return "[" + method + "]";
    }
}

